package cz.data.domain.market.mapping.service.impl;

import com.alibaba.fastjson.JSONObject;
import cz.data.common.exception.DataException;
import cz.data.common.support.db.core.PageResult;
import cz.data.common.support.db.driver.JdbcCustomOperation;
import cz.data.domain.driver.rpc.JdbcDriverFeign;
import cz.data.domain.market.mapping.utils.SqlBuilderUtil;
import cz.data.domain.market.model.entity.DataApiEntity;
import cz.data.domain.metadata.rpc.MetadataSourceFeign;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Map;

@Component
public class DataApiEngine {

    @Autowired
    private MetadataSourceFeign metadataSourceFeign;
    @Resource
    private JdbcDriverFeign jdbcDriverFeign;

    public PageResult<Map<String, Object>> execute(DataApiEntity dataApi, Map<String, Object> params) {
        String sourceId = dataApi.getExecuteConfig().getSourceId();
        // 参数
        Integer pageNum = Integer.parseInt(params.getOrDefault("pageNum", "1").toString());
        Integer pageSize = Integer.parseInt(params.getOrDefault("pageSize", "20").toString());
        SqlBuilderUtil.SqlFilterResult sqlFilterResult;
        try {
            sqlFilterResult = SqlBuilderUtil.getInstance().applyFilters(dataApi.getExecuteConfig().getSqlText(), params);
        } catch (Exception e) {
            throw new DataException("API调用动态构造SQL语句出错", e);
        }
        Map<String, Object> acceptedFilters = sqlFilterResult.getAcceptedFilters();
        PageResult<Map<String, Object>> pageResult;
        try {
            String sql = sqlFilterResult.getSql();
            JdbcCustomOperation operation = new JdbcCustomOperation();
            operation.setSource(sourceId);
            operation.setCommand(sql);
            operation.setParams(new JSONObject(acceptedFilters));
            operation.setPageNum(pageNum);
            operation.setPageSize(pageSize);
            pageResult = jdbcDriverFeign.instruct(operation);
        } catch (Exception e) {
            throw new DataException("API调用查询结果集出错", e);
        }
        return pageResult;
    }
}
